package com.chcit.mobile.mvp.hight.fragment;

import android.content.Intent;
import android.graphics.Canvas;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.ItemTouchHelper;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;

import com.chcit.mobile.app.base.ScanToolQueryFragment;
import com.google.android.material.tabs.TabLayout;

import android.widget.TextView;

import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.callback.ItemDragAndSwipeCallback;
import com.chad.library.adapter.base.listener.OnItemDragListener;
import com.chad.library.adapter.base.listener.OnItemSwipeListener;
import com.chcit.custom.view.edit.SuperInputEditText;
import com.chcit.custom.view.spinner.DropDownMenu;
import com.xuexiang.xui.widget.spinner.editspinner.EditSpinner;
import com.chcit.custom.view.text.one.SuperTextView;
import com.chcit.mobile.R;
import com.chcit.mobile.app.base.ScanFragment;
import com.chcit.mobile.app.utils.TimeDialogUtil;
import com.chcit.mobile.helper.HttpClientHelper;
import com.chcit.mobile.helper.recycler.RecycleViewDivider;
import com.chcit.mobile.mvp.common.model.MenuTypeEnum;
import com.chcit.mobile.mvp.entity.BpartnerBean;
import com.chcit.mobile.mvp.entity.HightRegisPackageBean;
import com.chcit.mobile.mvp.entity.PackageBean;
import com.chcit.mobile.mvp.entity.Statu;
import com.chcit.mobile.mvp.hight.adapter.HightCostAdapter;
import com.chcit.mobile.mvp.hight.adapter.HightCostRegisPackageAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.chcit.mobile.mvp.hight.di.component.DaggerHightCostComponent;
import com.chcit.mobile.mvp.hight.contract.HightCostContract;
import com.chcit.mobile.mvp.hight.presenter.HightCostPresenter;
import com.xuexiang.xui.widget.toast.XToast;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;


public class HightCostFragment extends ScanToolQueryFragment<HightCostPresenter> implements HightCostContract.View {

    @BindView(R.id.lv_hcr_list)
    RecyclerView mRecyclerView;
    @BindView(R.id.bt_hcr_ok)
    Button btOk;
    @BindView(R.id.ll_create_user)
    LinearLayout llCreateUser;
    @BindView(R.id.spinner_input_username)
    EditSpinner spinnerUsers;
    @BindView(R.id.tab_cost_layout)
    TabLayout mTabLayout;
    protected MenuTypeEnum type;

    @BindView(R.id.ddm_hight_bind_date)
    DropDownMenu mDropDownMenu;
    private SuperTextView tvDateFrom;
    private SuperTextView tvDateTo;
    private BpartnerBean bpartnerBean;
    private ArrayList<BpartnerBean> bpartners;
    private String headers[] = {"选择日期"};
    //private Integer userID;
    private Statu user;
    private HightCostAdapter mUnRegisterAdapter;
    private HightCostRegisPackageAdapter mRegisteredAdapter;
    
    private List<PackageBean> mUnRegisterList = new ArrayList<>();
    private List<HightRegisPackageBean> mRegisteredList = new ArrayList<>();
    public static HightCostFragment newInstance() {
        HightCostFragment fragment = new HightCostFragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerHightCostComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_hight_cost;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

//        if(getArguments() != null){
//            userID  = getArguments().getInt("userID");
//        }
        btQuery.setEnabled(false);
        mTabLayout.addTab(mTabLayout.newTab().setText("扫码详情"));
        mTabLayout.addTab(mTabLayout.newTab().setText("历史记录"));
        mTabLayout.addOnTabSelectedListener(new TabLayout.BaseOnTabSelectedListener(){

            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                    switch (tab.getPosition()){
                        case 0:
                            mRecyclerView.setAdapter(mUnRegisterAdapter);
                            break;
                        case 1:
                            getRegisListData();
                            mRecyclerView.setAdapter(mRegisteredAdapter);
                            break;
                    }
            }



            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        initSpinner();
        initRecyclerView();
        initDropDownMenu();
    }

    private void initSpinner() {
        mPresenter.queryUsers(list->{

            spinnerUsers.setOnItemClickListener((parent, view, position, id) -> {
                if (position > 0 && list.size() > position) {
                    user = spinnerUsers.getSelectItem();;
                }
            });
            Statu statu = new Statu();
            statu.setId(String.valueOf(HttpClientHelper.getSystemUser().getUserID()));
            int key = list.indexOf(statu);
            if(key >-1){
                user = list.get(key);
            }else{
                user = list.get(0);
            }
            if(user != null){
                spinnerUsers.setText(user.getName());
            }
            spinnerUsers.setItemData(list);
        });

    }

    private void initDropDownMenu() {
        final List<View> popupViews = new ArrayList<>();
        //日期选择
        final View dateView = getLayoutInflater().inflate(R.layout.pop_date, null);
        tvDateTo = dateView.findViewById(R.id.pop_date_drive);
        tvDateFrom = dateView.findViewById(R.id.pop_date_from);
        TextView ok = dateView.findViewById(R.id.ok);
        tvDateFrom.setCenterString(TimeDialogUtil.getBeforeDay(0));
        tvDateFrom.setOnClickListener(v -> TimeDialogUtil.showDatePickerDialog(getActivity(), 3, s->tvDateFrom.setCenterString(s), 0));
        tvDateTo.setOnClickListener(v -> TimeDialogUtil.showDatePickerDialog(getActivity(), 3, s->tvDateTo.setCenterString(s), 0));
        tvDateFrom.setOnClickListener(new View.OnClickListener() {
            Calendar calendar = Calendar.getInstance();
            @Override
            public void onClick(View v) {
                TimeDialogUtil.showDatePickerDialog(getActivity(), 3,
                        s->{
                            tvDateFrom.setCenterString(s);
                            ok.performClick();
                        },
                        0,calendar);
            }
        });
        tvDateTo.setOnClickListener(new View.OnClickListener() {
            Calendar calendar = Calendar.getInstance();
            @Override
            public void onClick(View v) {
                TimeDialogUtil.showDatePickerDialog(getActivity(), 3, s->{
                    tvDateTo.setCenterString(s);
                    ok.performClick();
                }, 0,calendar);


            }
        });

        ok.setOnClickListener(v -> {
            StringBuffer text = new StringBuffer();
            if(!tvDateFrom.getCenterString().isEmpty()){
                text.append("开始日期：");
                text.append(tvDateFrom.getCenterString()) ;
            }
            if(!tvDateTo.getCenterString().isEmpty()){
                text .append("\n结束日期："+ tvDateTo.getCenterString());
            }

            mDropDownMenu.setTabText(text==null? headers[0] : text.toString());
            mDropDownMenu.closeMenu();
        });
        popupViews.add(dateView);
        final TextView contentView = new TextView(getContext());
        contentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        contentView.setText("");
        //contentView.setBackgroundColor(getResources().getColor(R.color.gray));
        contentView.setGravity(Gravity.CENTER);
        contentView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
        final List<String> list = Collections.singletonList("开始日期：" + TimeDialogUtil.getBeforeDay(0));
        mDropDownMenu.setDropDownMenu(list, popupViews, contentView);
        tvDateTo.setRightImageViewClickListener(l -> {
            tvDateTo.setCenterString("");
        });
        tvDateFrom.setRightImageViewClickListener(l -> {
            tvDateFrom.setCenterString("");
        });

    }
    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        XToast.info(mContext,message).show();
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {

    }
    @Override
    protected void onBarcodeEventSuccess(String barcodeData) {
        vetPackageNo.setText(barcodeData);
        btQuery.performClick();
    }

    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);
        initEvent();
    }
    private void initRecyclerView(){

        mRegisteredAdapter = new HightCostRegisPackageAdapter(mRegisteredList);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mRecyclerView.addItemDecoration(new RecycleViewDivider(mContext, LinearLayoutManager.HORIZONTAL, R.drawable.item_drivide));
        mUnRegisterAdapter = new HightCostAdapter(mUnRegisterList);
        ItemDragAndSwipeCallback mItemDragAndSwipeCallback = new ItemDragAndSwipeCallback(mUnRegisterAdapter);
        ItemTouchHelper mItemTouchHelper = new ItemTouchHelper(mItemDragAndSwipeCallback);
        mItemTouchHelper.attachToRecyclerView(mRecyclerView);
        OnItemDragListener listener = new OnItemDragListener() {
            @Override
            public void onItemDragStart(RecyclerView.ViewHolder viewHolder, int pos) {
                BaseViewHolder holder = ((BaseViewHolder) viewHolder);
//                holder.setTextColor(R.id.tv, Color.WHITE);
            }

            @Override
            public void onItemDragMoving(RecyclerView.ViewHolder source, int from, RecyclerView.ViewHolder target, int to) {

            }

            @Override
            public void onItemDragEnd(RecyclerView.ViewHolder viewHolder, int pos) {
                BaseViewHolder holder = ((BaseViewHolder) viewHolder);
//                holder.setTextColor(R.id.tv, Color.BLACK);
            }
        };
        OnItemSwipeListener onItemSwipeListener = new OnItemSwipeListener() {
            @Override
            public void onItemSwipeStart(RecyclerView.ViewHolder viewHolder, int pos) {

            }

            @Override
            public void clearView(RecyclerView.ViewHolder viewHolder, int pos) {

            }

            //删除item
            @Override
            public void onItemSwiped(RecyclerView.ViewHolder viewHolder, int pos) {

            }

            @Override
            public void onItemSwipeMoving(Canvas canvas, RecyclerView.ViewHolder viewHolder, float dX, float dY, boolean isCurrentlyActive) {
                canvas.drawColor(ContextCompat.getColor(mContext, R.color.green));

            }
        };

        //mItemDragAndSwipeCallback.setDragMoveFlags(ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT | ItemTouchHelper.UP | ItemTouchHelper.DOWN);
        mItemDragAndSwipeCallback.setSwipeMoveFlags(ItemTouchHelper.START | ItemTouchHelper.END);
        // 开启滑动删除
        mUnRegisterAdapter.enableSwipeItem();
        mUnRegisterAdapter.setOnItemSwipeListener(onItemSwipeListener);
        // 开启拖拽
        mUnRegisterAdapter.enableDragItem(mItemTouchHelper);
        mUnRegisterAdapter.setOnItemDragListener(listener);
        mRecyclerView.setAdapter(mUnRegisterAdapter);
    }
    private void initEvent() {

        vetPackageNo.addTextChangedListener(textWatcher);
    }
    private void getRegisListData() {

        mPresenter.getRegistedPakcageInfo(tvDateFrom.getCenterTextView().getText().toString(),tvDateTo.getCenterTextView().getText().toString(),
                list->{
                    mRegisteredList.clear();
                    mRegisteredAdapter.addData(list);
                });
    }
    @OnClick({R.id.bt_common_query, R.id.bt_hcr_ok})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_common_query:
                PackageBean packageBean = new PackageBean(vetPackageNo.getText().toString());
                int position = mUnRegisterList.indexOf(packageBean);
                if(position >= 0){
                    new MaterialDialog.Builder(mContext)
                            .title("提示")
                            .content("该条码已被扫过，是否删除？")
                            .negativeText("删除")
                            .positiveText("取消")
                            .onNegative((dialog, which) -> {
                                mUnRegisterAdapter.remove(position);
                            })
                            .build()
                            .show();
                    return;
                }
                JSONObject params = new JSONObject();
                params.put("packageNo",vetPackageNo.getText().toString());
                // params.put("packageStatus","S");//在库
                params.put("warehouseId", HttpClientHelper.getSelectWareHouse().getId());
                mPresenter.getPakcageInfo(params, list->{
                    mUnRegisterAdapter.addData(list.get(0));
                    btOk.setEnabled(true);
                });
                break;
            case R.id.bt_hcr_ok:
                //arehouseId:1212,bpartnerId:121212,userCode:"23235gg",packageNo:["wewe","wewec"]}
                if(!(mUnRegisterList.size()>0)){
                    return;
                }
                JSONArray packages = new JSONArray();
                for(PackageBean p:mUnRegisterList){
                    packages.add(p.getPackageNo());
                }
                //        warehouseId:1000214
                //        userId:1000431
                //        packageNo:["(00)090000004000002502"]
                JSONObject requestParam = new JSONObject();
                requestParam.put("warehouseId", HttpClientHelper.getSelectWareHouse().getId());
                requestParam.put("packageNo",packages);
                switch (type) {
                    case HIGHT_CREAT:
                        requestParam.put("userId",user.getId());
                        mPresenter.createBorrowOrderByPackage(requestParam, list -> {
                            ArmsUtils.snackbarTextWithLong("登记成功！");
                            mUnRegisterAdapter.getData().clear();
                            mUnRegisterAdapter.notifyDataSetChanged();
                        });
                        break;
                    case HIGHT_REJECT:
                        mPresenter.borrowBackByPackage(requestParam, list -> {
                            ArmsUtils.snackbarTextWithLong("退回成功！");
                            mUnRegisterAdapter.getData().clear();
                            mUnRegisterAdapter.notifyDataSetChanged();
                        });
                        break;
                }

        }
    }
    private TextWatcher textWatcher = new TextWatcher() {
        int mEditTextHaveInputCount = 0 ;
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // EditText内容改变之后 内容为空时 个数减一 按钮改为不可以的背景*/
            if (TextUtils.isEmpty(s)) {
                mEditTextHaveInputCount--;
                if (mEditTextHaveInputCount == 0) {
                    btQuery.setEnabled(false);
                }
            }

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            //EditText最初内容为空 改变EditText内容时 个数加一
            if (TextUtils.isEmpty(s)) {

                mEditTextHaveInputCount++;
                // 判断个数是否到达要求
                int EDITTEXT_AMOUNT = 1;

                if (mEditTextHaveInputCount >= EDITTEXT_AMOUNT) {
                    btQuery.setEnabled(true);
                }
            }

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };
}
